package Thread;

/*
 * Author: JacksonCoder
 * FileName: SequentialPrinting
 * Version: 1.0.0
 * Date: 2025/1/22
 */

public class SequentialPrinting {

    private static final int MAX_NUMBER = 100;
    private static final int THREAD_COUNT = 5;
    private static int currentNumber = 0;
    private static final Object lock = new Object();

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(new Printer(i)).start();
        }
    }

    static class Printer implements Runnable {

        private final int threadId;

        public Printer(int threadId) {
            this.threadId = threadId;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    // 检查是否轮到当前线程打印
                    while (currentNumber % THREAD_COUNT != threadId) {
                        if (currentNumber > MAX_NUMBER) {
                            return;
                        }
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }

                    // 如果当前数字超过最大值，退出循环
                    if (currentNumber > MAX_NUMBER) {
                        lock.notifyAll();
                        return;
                    }

                    // 打印当前数字
                    System.out.println("Thread " + threadId + ": " + currentNumber);
                    currentNumber++;

                    // 通知其他线程
                    lock.notifyAll();
                }
            }
        }
    }

}
